package cn.wujiangbo.Thread;

import cn.wujiangbo.domain.User;
import cn.wujiangbo.mapper.UserMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

//添加用户测试数据的线程
public class AddUserRunnable implements Runnable{

    private UserMapper userMapper;
    private List<User> userList;
    private CountDownLatch latch;

    public AddUserRunnable(UserMapper userMapper, List<User> userList, CountDownLatch latch){
        this.userMapper = userMapper;
        this.userList = userList;
        this.latch = latch;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "：线程执行-开始");
        long t1 = System.currentTimeMillis();
        try {
            //数据太多需要分批次提交，这里以1000条提交一次为例
            int countItem = 1000;//每次提交的记录条数
            int userSize = userList.size();
            List<User> userListTemp = new ArrayList<>();
            for (int i = 0, n=userSize; i < n; i++) {
                User user= userList.get(i);
                userListTemp.add(user);
                if ((i>0 && i % countItem == 0) || i == userSize - 1) {
                    //每1000条记录提交一次
                    userMapper.insertBatch(userListTemp);
                    userListTemp.clear();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        long t2 = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + "线程执行-结束，批量插入数据" + userList.size() + "条，总耗时：" + (t2-t1) + "毫秒");
        latch.countDown();
    }
}
